from flask import render_template, g, redirect, request, jsonify, current_app, session, abort

from info import db, constants
from info.models import Category, News, User
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route("/other_news_list")
def other_news_list():
    """
    返回指定用户的发布新闻
    :return:
    """
    # 1. 获取数据
    other_id = request.args.get("user_id")
    page = request.args.get("p", 1)
    # 2. 校验数据
    if not all([other_id, page]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")
    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())

    data = {
        "news_list": news_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }
    return jsonify(errno=RET.OK, errmsg="ok", data=data)


@profile_blu.route("/other_info")
@user_login_data
def other_info():
    """
    其他用户展示
    :return:
    """
    user = g.user
    other_id = request.args.get("user_id")
    if not other_id:
        abort(404)
    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template("news/other.html", data=data)


@profile_blu.route("/user_follow")
@user_login_data
def user_follow():
    """
    用户个人关注列表
    :return:
    """
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route("/news_list")
@user_login_data
def news_lists():
    """
    新闻发布列表
    :return:
    """
    # 1. 获取页数
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_dict_li
    }
    return render_template("news/user_news_list.html", data=data)


@profile_blu.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    """
    新闻发布
    :return:
    """
    if request.method == "GET":
        # 加载新闻分类数据
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 定义列表保存分类数据
        categories_dicts = []
        for category in categories:
            # 获取字典
            cate_dict = category.to_dict()
            # 拼接内容
            categories_dicts.append(cate_dict)

        # 移除最新分类
        categories_dicts.pop(0)

        # 返回内容
        return render_template("news/user_news_release.html", data={"categories": categories_dicts})

    # 1. 获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    source = "个人发布"

    # 2. 校验参数
    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 读取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 4. 将图片上传到七牛云
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 5. 初始化新闻模型，并设置相关参数
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1 代表待审核状态
    news.status = 1

    # 6. 添加到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    # 6. 返回响应
    return jsonify(errno=RET.OK, errmsg="发布成功，待审核")


@profile_blu.route("/collection")
@user_login_data
def collection():
    """
    新闻收藏
    :return:
    """
    # 1. 获取页数
    page = request.args.get("p", 1)

    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 3. 查询用户指定页数的收藏的新闻
    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        pagenate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 当前页数
        current_page = pagenate.page
        # 总页数
        total_page = pagenate.pages
        # 获取分页数据
        news_list = pagenate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "collections": news_dict_li
    }
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/pass_info", methods=["GET", "POST"])
@user_login_data
def pass_info():
    """
    密码修改
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    if request.method == "GET":
        return render_template("news/user_pass_info.html")
    else:
        # 1. 获取数据
        old_password = request.json.get("old_password")
        new_password = request.json.get("new_password")

        # 2. 校验数据
        if not all([old_password, new_password]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 3. 获取当前用户登录

        if not user.check_password(old_password):
            return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

        # 设置新密码
        user.password = new_password
        return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route("/pic_info", methods=["GET", "POST"])
@user_login_data
def pic_info():
    """
    用户头像设置
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user": user.to_dict()})
    else:
        # 1. 获取上传文件
        try:
            avatar_file = request.files.get("avatar").read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="读取文件错误")

        # 2.上传头像
        try:
            key = storage(avatar_file)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

        # 3. 保存头像地址
        user.avatar_url = key
        return jsonify(errno=RET.OK, errmsg="上传头像成功", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route("/base_info", methods=["GET", "POST"])
@user_login_data
def base_info():
    """
    基本资料
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": user.to_dict()})
    else:
        # 1. 接收用户传过来的数据
        nick_name = request.json.get("nick_name")
        signature = request.json.get("signature")
        gender = request.json.get("gender")

        # 2. 校验参数
        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        if gender not in (["MAN", "WOMEN"]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 3. 更新并保存数据
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender

        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        # 将session中保存的数据进行实时更新
        session["nick_name"] = nick_name

        # 4.返回响应
        return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blu.route("/info")
@user_login_data
def user_info():
    """
    个人中心
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user": user.to_dict()
    }
    return render_template("news/user.html", data=data)
